package com.semidata.rtd.core.log;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.semidata.rtd.core.service.RegisterService;
import com.semidata.rtd.core.service.SendableService;

@RegisterService
public class LogService implements SendableService<LogEvent> {

	private LogBlockHandler blockHandler;
	private Map<String, LogEventHandler> map = new HashMap<>();
	private String root;

	public LogService(String root) {
		File dir = new File(root);
		if (dir.exists()) {
			if (!dir.isDirectory() || !dir.canExecute() || !dir.canWrite())
				throw new RuntimeException("can not write log in dir " + root);
		} else {
			if (!dir.mkdirs())
				throw new RuntimeException("can not write log in dir " + root);
		}
		this.root = root;
		blockHandler = new LogBlockHandler();
	}
	
	public boolean registerLogEventHandler(String name, Class<? extends LogEventHandler> handlerClass) {
		
		LogEventHandler handler;
		try {
			handler = handlerClass.getConstructor(LogBlockHandler.class).newInstance(blockHandler);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		if (!handler.setRoot(root))
			return false;
		map.put(name, handler);
		return true;
	}

	@Override
	public void send(LogEvent event) {
		
		String type = event.getType();
		LogEventHandler handler = map.get(type);
		if (handler != null)
			handler.send(event);
	}
	
	
	
	
	@Override
	public void start() {
		blockHandler.start();
		for (Entry<String, LogEventHandler> entry : map.entrySet()) {
			entry.getValue().start();
		}
	}

	@Override
	public void stop() {
		for (Entry<String, LogEventHandler> entry : map.entrySet()) {
			entry.getValue().stop();
		}
		blockHandler.stop();
	}

	

}
